<?php
/**
 * @function：令牌权限认证
 * @Author: 倪银龙
 * @Mail niyinlong@126.com
 * @Date: 15-10-1
 * @Time: 上午9:00
 * @Blog: Http://www.thinkwechat.cn
 */
namespace wechat;
use wechat\curl;

/**
 *获取accesstoken
 * appid appsecret 等在配置文件里可以进行配置
 * apptoken 放在缓存数组中
 */
class accesstoken{
	/*
	*获取token
	*/
	public function getAccessToken($type = 'app'){
            //从数据库中获取
            if ($type == 'app') {
                $token = cache("apptoken");
            } else {
                $token = cache("txltoken");
            }
            //如果为空则从服务器端重新获取
            if(empty($token) || !$this->checkToken($token)){
                $token = $this->getTokenByUrl($type);
            //如果数据库中有数据则验证是否有效
            }
            $accessToken = json_decode($token, true);
            return $accessToken["access_token"];
	}
        
	/*
	*通过URL获取token操作方法
	*/
	private function getTokenByUrl($type = 'app'){
                $appid = $this->getAppid();
                if ($type == 'app') {
                    $appsecret = $this->getAppSecret();
                } else {
                    $appsecret = $this->getTxlSecret();
                }
//                dump($appid);dump($appsecret);
		$url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid='.$appid.'&corpsecret='.$appsecret;
		$accessToken = curl::callWebServer($url, '','get');
//                dump($accessToken);
		$accessToken['time'] = time();
                $accessTokenJson = json_encode($accessToken);
                 if ($type == 'app') {
                    cache("apptoken",$accessTokenJson);
                } else {
                    cache("txltoken",$accessTokenJson);
                }
                return $accessTokenJson;
	}
        
        
	/*
	*获取APPID
	*/
	private function getAppid(){
		
            return config('QYWX_APP_ID');
	}
	/*
	*获取APPsecret
	*/
	private function getAppSecret(){
            return config('QYWX_APP_SECRET');
	}
        
        /*
	*获取TXLsecret
	*/
	private function getTxlSecret(){
            return config('QYWX_TXL_SECRET');
	}

	/*
	*检测token是否有效
	*$token 是json格式
	*/
	private function checkToken($token){
		$accessToken = json_decode($token, true);
                if(time() - $accessToken['time'] + 100 < $accessToken['expires_in']){
                    return true;
                } else {
                   return false; 
                }
	}
}
?>